Component({
  properties: {
    artworks: {
      type: Array,
      value: [],
      observer: 'distributeArtworks', // 监听 artworks 变化
    },
    currentView: {
      type: String,
      value: 'grid2',
    },
  },

  data: {
    leftColumn: [],
    rightColumn: [],
    leftHeight: 0,
    rightHeight: 0,
  },

  methods: {
    async distributeArtworks() {
      const { artworks } = this.properties;
      let leftColumn = [];
      let rightColumn = [];
      let leftHeight = 0;
      let rightHeight = 0;
  
      // 创建一个 Promise 数组，用于等待所有图片信息获取完成
      const promises = artworks.map((artwork) => {
        return new Promise((resolve) => {
          wx.getImageInfo({
            src: artwork.primaryImageSmallUrl,
            success: (res) => {
              const { width, height } = res;
              const screenWidth = wx.getWindowInfo().screenWidth;
              const imageHeight = (screenWidth / 2) * (height / width);
              artwork.imageHeight = imageHeight;
  
              if (leftHeight <= rightHeight) {
                leftColumn.push(artwork);
                leftHeight += imageHeight;
              } else {
                rightColumn.push(artwork);
                rightHeight += imageHeight;
              }
  
              // console.log("艺术作品左边的数据：" + leftColumn);
              // console.log("艺术作品右边的数据：" + rightColumn);
              resolve(); // 标记当前图片信息获取完成
            },
            fail: (err) => {
              console.error("获取图片信息失败:", err);
              resolve(); // 即使失败也继续执行
            },
          });
        });
      });
  
      // 等待所有图片信息获取完成
      await Promise.all(promises);
  
      // console.log("-------------------------------------------");
      // console.log("分配结束之后艺术作品左边的数据：" + leftColumn);
      // console.log("分配结束之后艺术作品右边的数据：" + rightColumn);
      this.setData({ leftColumn, rightColumn });
    },

    goToDetail(e) {
      const artWorkId = e.currentTarget.dataset.id;
      wx.navigateTo({
        url: `/pages/artwork/detail/detail?artWorkId=${artWorkId}`,
      });
    },
  },
});